package uk.gov.swmprobation.cplite;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

public class LocationServicesWithClient extends Service implements LocationListener,ConnectionCallbacks, OnConnectionFailedListener {

	static LocationClient locationClient;
	LocationRequest locationRequest;
	static final int interval = 1000*60*1;
	static final int fastest_interval = 1000*30;
	public static final int FEW_MINUTES = 1000 * 60 * 10;
	
	static Location latestLocation;
	
	@Override
	public void onCreate(){
		locationClient = new LocationClient(this, this, this);
		locationClient.connect();
		locationRequest = LocationRequest.create();
		locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
		locationRequest.setInterval(interval);
		locationRequest.setFastestInterval(fastest_interval);
		latestLocation = null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
	    return START_STICKY;
	}
	
	public void onDestroy(){
		if (locationClient.isConnected()) {
            /*
             * Remove location updates for a listener.
             * The current Activity is the listener, so
             * the argument is "this".
             */
            locationClient.removeLocationUpdates(this);
            locationClient.disconnect();
        }
	}
	
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onConnected(Bundle connectionHint) {
		locationClient.requestLocationUpdates(locationRequest, this);		
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onLocationChanged(Location location) {
		latestLocation = location;	
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	public static boolean locationAvailable(){
		if (latestLocation==null){
			return false;
		}
		if (System.currentTimeMillis() - latestLocation.getTime() > FEW_MINUTES){
			return false;
		}
		return true;
	}
	
	public static double getLocationLat(){
		return latestLocation.getLatitude() ;
	}
	
	public static double getLocationLng(){
		return latestLocation.getLongitude();
	}
	
	public static long getLocationTime(){
		return latestLocation.getTime();
	}
	
}

